SpringBootTest에서 Controller 테스트 할 경우, Transactional하게 하기
Question
RestAssured로 RestController 메서드를 테스트 중인데 혹시 이거 때문에 Transactional 하지 않은건가?
GPT Answer
When you use RestAssured for testing your RestController methods, you're making HTTP calls to your application, which means the test is running in a different process or thread than your application. In this scenario, the @Transactional annotation in your test class won't have any effect on the transactions executed by your application.
RestAssured tests are more like integration tests, where your application is tested as a whole, including the HTTP layer. Due to the nature of these tests, they don't run within the same transactional context as the application code.
If you want to test your RestController methods within a transactional context and have the transactions roll back after each test, you can use the @WebMvcTest annotation along with @Autowired for a MockMvc instance. This way, you can test the controller methods without making actual HTTP calls, and the @Transactional annotation should work as expected.
Here's an example:
@RunWith(SpringRunner.class)
@WebMvcTest(YourController.class)
@Transactional
public class YourControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void yourTestMethod() throws Exception {
mockMvc.perform(get("/your/endpoint"))
.andExpect(status().isOk());
}
}
In this example, the @WebMvcTest annotation loads only the specified controller and its dependencies, while the @Transactional annotation will ensure that any changes made during the test are rolled back after the test finishes.